<template>
  <div>
    <el-drawer
      :title="title"
      :visible.sync="childFormVisible"
      append-to-body
      :wrapper-closable="false"
      size="60%"
      class="mt-dialog"
      @close="hide"
    >
      <div style="margin: 20px;">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form ref="f2" :model="CRMShippingInquiryTemp" :rules="rules" label-position="right" label-width="120px" style="width: 438px;display: inline-block;">
              <el-form-item label="快递公司">
                <el-select v-model="crmshippingcompany_id" placeholder="选择快递公司" @change="handleGetShippingCarrier">
                  <el-option
                    v-for="item in crmshippingcomanys"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <el-select v-if="crmshippingcompany_id !== ''" v-model="CRMShippingInquiryTemp.crmshippingcarrier_id" placeholder="选择快递">
                  <el-option
                    v-for="item in crmcarriers"
                    :key="item.id"
                    :label="item.cnname"
                    :value="item.id"
                  />
                </el-select>
                <span v-if="CRMShippingInquiryTemp.crmshippingcarrier_id !== ''">{{ CRMShippingInquiryTemp.crmshippingcarrier_id }}</span>
                <el-button icon="el-icon-setting" type="text" @click="handleManageShippingCompany" />
              </el-form-item>
              <el-form-item label="快递单号" prop="product_name">
                <el-input v-model="CRMShippingInquiryTemp.tracking_no" size="mini" />
              </el-form-item>
              <el-form-item label="产品名称" prop="product_name">
                <el-input v-model="CRMShippingInquiryTemp.product_name" size="mini" />
              </el-form-item>
              <el-form-item label="价格 (USD)" prop="price_usd">
                <el-input v-model.number="CRMShippingInquiryTemp.price_usd" size="mini" type="number" />
              </el-form-item>
              <el-form-item label="图片" prop="image">
                <el-image v-for="image in CRMShippingInquiryTemp.image" v-if="CRMShippingInquiryTemp.image.length" :key="image" :preview-src-list="[image]" :src="image" style="width: 50px" />
                <crmfilesmanager color="#1890ff" class="editor-upload-btn" @insert="handleInsertFile" />
                <el-input v-model="imageUrl" placeholder="图片链接" size="mini">
                  <el-button slot="append" icon="el-icon-plus" @click="handelAddImageFromUrl" />
                </el-input>
              </el-form-item>
              <el-form-item label="毛重" prop="packages_weight">
                <el-input v-model.number="CRMShippingInquiryTemp.packages_weight" size="mini" type="number" />
              </el-form-item>
              <el-form-item label="长宽高" prop="packages_length">
                <el-input v-model.number="CRMShippingInquiryTemp.packages_length" size="mini" style="width: 65px" placeholder="长(米)" />
                x<el-input v-model.number="CRMShippingInquiryTemp.packages_width" size="mini" style="width: 65px" placeholder="宽(米)" />
                x<el-input v-model.number="CRMShippingInquiryTemp.packages_hight" size="mini" style="width: 65px" placeholder="高(米)" />
              </el-form-item>
              <el-form-item label="体积 (立方米)" prop="packages_volume">
                <el-input v-model.number="CRMShippingInquiryTemp.packages_volume" size="mini" type="number" />
              </el-form-item>
              <el-form-item label="数量" prop="packages_quantity">
                <el-input v-model.number="CRMShippingInquiryTemp.packages_quantity" size="mini" type="number" />
              </el-form-item>
              <el-form-item label="客户要求" prop="customer_requirements">
                <el-input v-model="CRMShippingInquiryTemp.customer_requirements" size="mini" type="textarea" />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form ref="f1" :model="CRMShippingInquiryTemp" :rules="rules" label-position="right" label-width="80px" style="width: 438px;display: inline-block;">
              <el-form-item label="离岸港口" prop="departure_port">
                <el-input v-model="CRMShippingInquiryTemp.departure_port" size="mini" />
              </el-form-item>
              <el-form-item label="目的港口" prop="destination_port">
                <el-input v-model="CRMShippingInquiryTemp.destination_port" size="mini" />
              </el-form-item>
              <el-form-item label="国家" prop="country">
                <el-input v-model="CRMShippingInquiryTemp.country" size="mini" />
              </el-form-item>
              <el-form-item label="邮编" prop="zip">
                <el-input v-model="CRMShippingInquiryTemp.zip" size="mini" />
              </el-form-item>
              <el-form-item label="州" prop="state">
                <el-input v-model="CRMShippingInquiryTemp.state" size="mini" />
              </el-form-item>
              <el-form-item label="城市" prop="city">
                <el-input v-model="CRMShippingInquiryTemp.city" size="mini" />
              </el-form-item>
              <el-form-item label="地址" prop="address">
                <el-input v-model="CRMShippingInquiryTemp.address" size="mini" type="textarea" />
              </el-form-item>
              <el-form-item label="带电机" prop="has_electric_moto">
                <el-switch v-model="CRMShippingInquiryTemp.has_electric_moto" />
              </el-form-item>
              <el-form-item label="带油" prop="has_oil">
                <el-switch v-model="CRMShippingInquiryTemp.has_oil" />
              </el-form-item>
              <el-form-item label="走什么船" prop="expected_shipping_vessel">
                <el-input v-model="CRMShippingInquiryTemp.expected_shipping_vessel" size="mini" />
              </el-form-item>

              <el-form-item label="备注" prop="shipping_note">
                <el-input v-model="CRMShippingInquiryTemp.shipping_note" size="mini" type="textarea" />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-button @click="childFormVisible = false">取 消</el-button>
          <el-button type="primary" :loading="editloading" @click="confirm">确 定</el-button>
        </el-row>
      </div>
    </el-drawer>
    <el-row style="justify-content: left;display: flex; ">
      <el-button round size="mini" type="primary" @click="handleShowEdit">添加报价
      </el-button>
    </el-row>
    <el-table
      v-loading="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      :default-sort="{prop: 'create_at', order: 'descending'}"
      style="width: 100%"
    >
      <el-table-column align="center" label="图片" width="150" prop="image">
        <template slot-scope="scope">
          <img v-if="scope.row.image.length" :src="scope.row.image" alt="product image" style="width: 100px; height: auto;">
          <el-image :preview-src-list="scope.row.image" :src="scope.row.image[0]" />
        </template>
      </el-table-column>
      <el-table-column align="left" fixed label="产品/单号" width="200" prop="product_name" sortable="custom">
        <template slot-scope="scope">
          <span style="display: block">{{ scope.row.product_name }}</span>
          <span style="display: block">
            <span>{{ scope.row.tracking_no }}</span>
            <el-link
              v-if="scope.row.tracking_no"
              :href="`https://t.17track.net/en#nums=${scope.row.tracking_no}`"
              target="_blank"
              type="primary"
              style="margin-left: 5px;"
              :underline="false"
            >
              <i class="el-icon-link" /> 查询
            </el-link>
          </span>
          <span style="font-size: xx-small;display: block"> {{ scope.row.create_at }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="简要信息" width="120" prop="price_usd">
        <template slot-scope="scope">
          <div style="font-size: 12px; line-height: 1.8;">
            <div><span style="color: #909399;">金额:</span> ${{ scope.row.price_usd }}</div>
            <div><span style="color: #909399;">数量:</span> {{ scope.row.packages_quantity }}</div>
            <div><span style="color: #909399;">重量:</span> {{ scope.row.packages_weight }}</div>
          </div>
        </template>
      </el-table-column>
      <!--      <el-table-column align="center" label="数量" width="100" prop="packages_quantity">-->
      <!--      </el-table-column>-->
      <!--      <el-table-column align="center" label="毛重" width="100" prop="packages_weight" sortable="custom">-->
      <!--      </el-table-column>-->

      <el-table-column align="center" label="包装信息" width="150" prop="packages_length">
        <template slot-scope="scope">
          <div style="font-size: 12px; line-height: 1.8;">
            <div><span style="color: #909399;">长宽高/米:</span> {{ scope.row.packages_length }}x{{ scope.row.packages_width }}x{{ scope.row.packages_hight }}</div>
            <div><span style="color: #909399;">包装体积:</span> {{ scope.row.packages_volume }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="港口信息" width="200" prop="departure_port">
        <template slot-scope="scope">
          <div style="font-size: 12px; line-height: 1.8;">
            <div><span style="color: #909399;">离岸港口:</span> {{ scope.row.departure_port }}</div>
            <div><span style="color: #909399;">目的港口:</span> {{ scope.row.destination_port }}</div>
            <div><span style="color: #909399;">预计货船:</span> {{ scope.row.expected_shipping_vessel }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="其他信息" width="120" prop="has_electric_moto">
        <template slot-scope="scope">
          <div style="font-size: 12px; line-height: 1.8;">
            <div><span style="color: #909399;">邮编:</span> {{ scope.row.zip }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="客户要求" width="250" prop="customer_requirements" />
      <el-table-column align="center" label="其他备注信息" width="250" prop="shipping_note" />
      <!--      <el-table-column align="center" label="目的港口" width="200" prop="destination_port">-->
      <!--      </el-table-column>-->
      <el-table-column align="center" label="地址信息" width="250" prop="country">
        <template slot-scope="scope">
          <div style="font-size: 12px; line-height: 1.8;">
            <div><span style="color: #909399;">国家:</span> {{ scope.row.country }} {{ scope.row.state }} {{ scope.row.city }}</div>
            <div><span style="color: #909399;">地址:</span> {{ scope.row.address }}</div>
            <div><span style="color: #909399;">邮编:</span> {{ scope.row.zip }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEditFromTable(scope.row)">订舱信息</el-button>
          <el-button type="text" size="small" @click="handleEditFromTable(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDeleteFromTable(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handlePageChange"
      />
    </el-table>
    <crmshippingcompany :crmshipping-company-visible="crmshippingCompanyVisible" @close="crmshippingCompanyVisible=false" />
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmshippinginquiry'
import { Get as GetShippingCompany } from '@/api/crm/crmshippingcompany'
import { Get as GetShippingCarrier } from '@/api/crm/crmshippingcarrier'
import qs from 'qs'
import Crmshippingcompany from '../crmshippingcompany'
import Crmfilesmanager from '../../../components/crmfilesmanager'
const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmshippinginquiry',
  components: { Crmfilesmanager, Crmshippingcompany },
  props: ['order_data'],
  data() {
    return {
      title: '物流信息',
      childFormVisible: false,
      listLoading: false,
      editloading: false,
      data: [],
      // 这里定义校验规则
      rules: {
        // 为需要校验的字段添加规则，例如:
        product_name: [{ required: false, message: '请输入产品名称', trigger: 'blur' }]
      },
      action: 'create',
      imageUrl: null,
      crmshippingCompanyVisible: false,
      crmshippingcompany_id: '',
      crmshippingcomanys: [],
      crmcarriers: [],
      CRMShippingInquiryTemp: {
        crmshippingcarrier_id: '',
        tracking_no: '',
        product_name: '',
        price_usd: 0,
        image: [],
        packages_weight: 1,
        packages_length: 1,
        packages_hight: 1,
        packages_width: 1,
        packages_volume: 1,
        packages_quantity: 1,
        departure_port: '',
        destination_port: '',
        country: '',
        zip: '',
        state: '',
        city: '',
        address: '',
        has_electric_moto: false,
        has_oil: false,
        expected_shipping_vessel: '',
        customer_requirements: '',
        shipping_note: ''
        // 注意: creator 和 project 可能需要特殊处理，例如使用选择器
      },
      kwInput: '',
      order_by: '',
      order_desc: orderMapper[0],
      // pagination
      pagesize: 20,
      page: 1,
      total: 0
    }
  },
  watch: {
    order_data: {
      handler(v) {
        this.title = '订单:' + v.order_no + '物流信息'
        this.getList()
      },
      immediate: true // 立即触发一次 handler
    }
  },
  created() {
    this.handleGetShipingCompany()
  },
  methods: {
    handleInsertFile(item) {
      // 如果CRMShippingInquiryTemp.image 中没有item.url则插入
      if (!this.CRMShippingInquiryTemp.image.includes(item.url)) {
        this.CRMShippingInquiryTemp.image.push(item.url)
        console.log(this.CRMShippingInquiryTemp.image)
      }
    },
    handelAddImageFromUrl() {
      if (this.imageUrl === '') return
      if (!this.CRMShippingInquiryTemp.image.includes(this.imageUrl)) {
        this.CRMShippingInquiryTemp.image.push(this.imageUrl)
        console.log(this.CRMShippingInquiryTemp.image)
      }
    },
    handleManageShippingCompany() {
      this.crmshippingCompanyVisible = true
    },
    handleGetShippingCarrier() {
      GetShippingCarrier(null, qs.stringify({
        kw: '',
        crmshippingcompany_id: this.crmshippingcompany_id,
        pagesize: 100,
        page: 1
      })).then(response => {
        this.crmcarriers = response.data.data
      })
    },
    handleGetShipingCompany() {
      GetShippingCompany(null, qs.stringify({
        kw: '',
        pagesize: 100,
        page: 1
      })).then(response => {
        this.crmshippingcomanys = response.data.data
      })
    },
    handleEditFromTable(row) {
      Object.keys(this.CRMShippingInquiryTemp).forEach(key => {
        if (row[key] !== undefined) this.CRMShippingInquiryTemp[key] = row[key]
      })
      this.CRMShippingInquiryTemp.id = row.id
      this.action = 'edit'
      this.title = '编辑报价' + row.product_name + 'ID:' + row.id
      this.childFormVisible = true
    },
    handleDeleteFromTable(row) {
      this.CRMShippingInquiryTemp.id = row.id
      this.action = 'delete'
      this.$confirm(`确认要删除报价  ${row.product_name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.confirm()
      }).catch(() => {
      })
    },
    readFileAsBase64(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.imageUrl = e.target.result
        this.CRMShippingInquiryTemp.file = this.imageUrl
      }
      reader.readAsDataURL(file)
    },
    handlePaste(event) {
      const items = (event.clipboardData || event.originalEvent.clipboardData).items
      for (const item of items) {
        if (item.type.indexOf('image') === 0) {
          const file = item.getAsFile()
          this.readFileAsBase64(file)
          // this.temp.file = file
          // this.imageUrl = URL.createObjectURL(file);
          // console.log(this.imageUrl)
        }
      }
    },
    handleShowEdit() {
      this.childFormVisible = true
      this.action = 'create'
      this.title = '订单:' + this.order_data.order_no + '新增物流信息'
    },
    resetTemp() {
      this.CRMShippingInquiryTemp = {
        crmshippingcarrier_id: '',
        tracking_no: '',
        product_name: '',
        price_usd: 0,
        image: [],
        packages_weight: 1,
        packages_length: 1,
        packages_hight: 1,
        packages_width: 1,
        packages_volume: 1,
        packages_quantity: 1,
        departure_port: '',
        destination_port: '',
        country: '',
        zip: '',
        state: '',
        city: '',
        address: '',
        has_electric_moto: false,
        has_oil: false,
        expected_shipping_vessel: '',
        customer_requirements: '',
        shipping_note: ''
        // 注意: creator 和 project 可能需要特殊处理，例如使用选择器
      }
      this.imageUrl = ''
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        crmorder_id: this.order_data.id,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    confirm() {
      switch (this.action) {
        case 'create':
          this.editloading = true
          this.CRMShippingInquiryTemp.crmorder_id = this.order_data.id
          Post(this.CRMShippingInquiryTemp).then((response) => {
            this.childFormVisible = false
            this.editloading = false
            this.$emit('reload')
            this.notify('添加成功')
            this.getList()
          })
          break
        case 'delete':
          Delete(this.CRMShippingInquiryTemp.id).then((response) => {
            this.childFormVisible = false
            this.$emit('reload')
            this.resetTemp()
            this.notify('删除成功')
            this.getList()
          })
          break
        case 'edit':
          this.editloading = true
          Put(this.CRMShippingInquiryTemp.id, this.CRMShippingInquiryTemp).then((response) => {
            this.childFormVisible = false
            this.editloading = true
            this.$emit('reload')
            this.resetTemp()
            this.notify('修改成功')
            this.getList()
          })
          break
      }
    },
    cancel() {
      this.childFormVisible = false
    },
    hide() {
      this.$emit('close', false)
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    notify(message) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: 2000
      })
    }
  }
}
</script>

<style scoped>
  .paste-area {
    border: 2px dashed #ccc;
    padding: 20px;
    text-align: center;
  }
  .mt-dialog >>> span.el-dialog__title {
    word-break: normal;
    width: auto;
    display: block;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow: hidden;
  }
</style>
